<?php

namespace app\admin\controller;

use app\admin\model\CategorySoft as CateSoft;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 任务配置管理
 *
 * @icon fa fa-circle-o
 */
class TaskConfig extends Backend
{

    /**
     * TaskConfig模型对象
     * @var \app\admin\model\TaskConfig
     */
    protected $model = null;
    protected $relationSearch = true;

    //快速搜索字段
    protected $searchFields = 'Name';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\TaskConfig;
        $this->view->assign("paramsTypeList", $this->model->getParamsTypeList());

    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with('paramstype')
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

           // dump($list);die;
           // dump($list->items());die;
            $redis = new \Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->select(2);
           // $redis->zIncrBy('task_config_'.date('Y-m-d'),1, $param['target']);
            $items_arr = $list->items();
            foreach($items_arr as $k=>$v){
                $items_arr[$k]['analyze']='>>>';
                $actual_count = $redis->zScore('task_config_'.date('Y-m-d'),$v['Id']);
                $items_arr[$k]['count_actual'] = $actual_count?:0;
                $items_arr[$k]['click_nums'] = 0;
                $items_arr[$k]['actual_quantity'] = 0;
            }

            $result = array("total" => $list->total(), "rows" => $items_arr);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 实际执行数量
     */
    public function actual_quantity(){
        $data= $this->curl_get('http://task.phckz.730893.com/admin/configdis');
        $data=json_decode($data,true);
//        dump($data);die;
        $datas = $data['data']['data'];
        return json($datas);
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(isset($params['params_type_id']) && $params['params_type_id'] == 4){//快排任务特殊处理
                $keyWord = $params['keyWord'] ??'';
                $keyWordLink = $params['keyWordLink'] ??'';
                $keyWordTitle = $params['keyWordTitle'] ??'';
                if(!$keyWord || !$keyWordLink || !$keyWordTitle){
                    $this->error('参数不完整');
                }
                $params['Detail'] = $this->getActionStr($keyWord,$keyWordLink,$keyWordTitle);
                unset($params['keyWord'],$params['keyWordLink'],$params['keyWordTitle']);
            }
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $params['DateEnd'] = date('Y-m-d H:i:s',strtotime($params['DateEnd'])+86400-1);
                   // dump($params);die;
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = \app\admin\model\ParamsType::column('id,name');
        array_push($list,'请选择');
        $this->view->assign(
            'paramsTypeList',
            build_select(
                'row[params_type_id]',
                array_reverse($list,true),
                ['class' => 'form-control selectpicker']
            )
        );
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if(isset($params['params_type_id']) && $params['params_type_id'] == 4){//快排任务特殊处理
                $keyWord = $params['keyWord'] ??'';
                $keyWordLink = $params['keyWordLink'] ??'';
                $keyWordTitle = $params['keyWordTitle'] ??'';
                if(isset($params['Detail']) && empty($params['Detail'])){
                    if(!$keyWord || !$keyWordLink || !$keyWordTitle){
                        $this->error('参数不完整');
                    }
                    $params['Detail'] = $this->getActionStr($keyWord,$keyWordLink,$keyWordTitle);
                }
                unset($params['keyWord'],$params['keyWordLink'],$params['keyWordTitle']);
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['DateEnd'] = date('Y-m-d H:i:s',strtotime($params['DateEnd'])+86400-1);
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = \app\admin\model\ParamsType::column('id,name');
        array_push($list,'请选择');
        $this->view->assign(
            'paramsTypeList',
            build_select(
                'row[params_type_id]',
                array_reverse($list,true),
                $row['params_type_id'],
                ['class' => 'form-control selectpicker']
            )
        );
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public static function curl_get($url){
       $testurl = $url;
       $ch = curl_init();
       curl_setopt($ch, CURLOPT_URL, $testurl);
        //参数为1表示传输数据，为0表示直接输出显示。
       curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //参数为0表示不带头文件，为1表示带头文件
       curl_setopt($ch, CURLOPT_HEADER,0);
       $output = curl_exec($ch);
       curl_close($ch);
       return $output;
    }

    private function getActionStr($keyWord,$keyWordLink,$keyWordTitle)
    {
        $keyWordArr = [
            "key"=>$keyWord,
            "count"=>1,
            "delay"=>3,
            "script"=>"",
            "operation"=>"paste"
        ];
        $page1 = [
            "count"=> "1",
            "delay"=> 3,
            "script"=> "(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var item = document.getElementById('su'); var rc = item.getBoundingClientRect(); var href = ''; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); return res; })();",
            "sub-page"=> [
                "duration"=> 3,
                "operation"=> "browse"
            ],
            "operation"=> "click"
        ];
        $page1Click = [
            "exit"=> true,
            "count"=> "1",
            "delay"=> 10,
            "script"=> "(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var left = document.getElementById('content_left'); if(left) { var items = left.getElementsByClassName('result'); if(items.length > 0) { for(var i = 0; i < items.length; ++i) { var item = items[i]; var targeth = item.getElementsByClassName('t'); if(targeth.length > 0) { var targeta = targeth[0].getElementsByTagName('a'); var showurl = item.getElementsByClassName('c-showurl'); var tool = item.getElementsByClassName('c-tools'); if(targeta.length > 0 && showurl.length > 0 && tool.length > 0) { var text = showurl[0].innerText; var data = JSON.parse(tool[0].getAttribute('data-tools')); var title = data.title; if(text == '".$keyWordLink."' && title == '".$keyWordTitle."') { var rc = targeta[0].getBoundingClientRect(); var href = items[i].href; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); break; } } } } } } return res; })();",
            "sub-page"=> [
                "duration"=> rand(31,44),
                "operation"=> "browse"
            ],
            "operation"=> "click"
        ];
        $operations = [
            [
                "count"=>"1",
                "script"=>"(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var item = document.getElementById('kw'); var rc = item.getBoundingClientRect(); var href = ''; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); return res; })();",
                "sub-page"=>[
                    "duration"=>3,
                    "operation"=>"browse"
                ],
                "operation"=>"click"
            ]
        ];
        array_push($operations,$keyWordArr,$page1,$page1Click);
        for ($i = 1; $i <= 9; $i++){
            $nextPage = [
                "count"=> "1",
                "delay"=> 10,
                "script"=> "(function() { var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var items = document.getElementsByClassName('n'); if(items && items.length > 0) { for(var i = 0; i < items.length; ++i) { var text = items[i].innerText; if(text.indexOf('下') != -1) { var rc = items[i].getBoundingClientRect(); if (rc.width == 0 || rc.height == 0) { continue; } var href = items[i].href; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); } } } return res; })();",
                "sub-page"=> [
                    "duration"=> 10,
                    "operation"=> "browse"
                ],
                "operation"=> "click"
            ];
            array_push($operations,$nextPage);
            $clickArr = [
                "exit"=> true,
                "count"=> "1",
                "delay"=> 10,
                "script"=> "(function(){ var res = []; var sctop = document.documentElement.scrollTop || document.body.scrollTop; res.push(['scrollTop', sctop]); var left = document.getElementById('content_left'); if(left) { var items = left.getElementsByClassName('result'); if(items.length > 0) { for(var i = 0; i < items.length; ++i) { var item = items[i]; var targeth = item.getElementsByClassName('t'); if(targeth.length > 0) { var targeta = targeth[0].getElementsByTagName('a'); var showurl = item.getElementsByClassName('c-showurl'); var tool = item.getElementsByClassName('c-tools'); if(targeta.length > 0 && showurl.length > 0 && tool.length > 0) { var text = showurl[0].innerText; var data = JSON.parse(tool[0].getAttribute('data-tools')); var title = data.title; if(text == '".$keyWordLink."' && title == '".$keyWordTitle."') { var rc = targeta[0].getBoundingClientRect(); var href = items[i].href; res.push(['item', rc.left, rc.top, rc.width, rc.height, href]); break; } } } } } } return res; })();",
                "sub-page"=> [
                    "duration"=> rand(31,44),
                    "operation"=> "browse"
                ],
                "operation"=> "click"
            ];
            array_push($operations,$clickArr);
        }

        $action = [
            "url"=> "https://www.baidu.com/?tn=67005728_2_oem_dg",
            "mode"=> "load",
            "duration"=> 90,
            "operations"=> $operations
        ];
        $arr = [
            "actions"=>[$action]
        ];
        return json_encode($arr,JSON_UNESCAPED_UNICODE);
    }
}
